package cn.bugstack.domain.strategy.service.rule.chain.impl;

import cn.bugstack.domain.strategy.repository.IStrategyRepository;
import cn.bugstack.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.bugstack.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import cn.bugstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Zchy
 * @Description: 抽奖前黑名单过滤链
 * @DateTime: 10/29/2024 5:16 PM
 **/
@Slf4j
@Component("rule_blacklist")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BlackListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultLogicChainFactory.StrategyAwardVo logic(Long strategyId, String userId) {
        log.info("抽奖责任链-黑名单过滤 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        //查询规则配置
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        if (splitRuleValue.length != 2) {
            throw new IllegalArgumentException("ruleValue 配置错误" + strategyId + ruleModel());
        }
        List<String> blackList = Arrays.asList(splitRuleValue[1].split(Constants.SPLIT));
        for(String blackUserId : blackList){
            if(blackUserId.equals(String.valueOf(userId))){
                log.info("抽奖责任链-黑名单结束 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
                return DefaultLogicChainFactory.StrategyAwardVo.builder()
                        .awardId(Integer.valueOf(splitRuleValue[0]))
                        .ruleModel(ruleModel())
                        // 写入默认配置黑名单奖品值 0.01 ~ 1 积分，也可以配置到数据库表中
                        .awardRuleValue("0.01,1")
                        .build();
            }
        }
        return next().logic(strategyId, userId);
    }

    @Override
    protected String ruleModel() {
        return "rule_blacklist";
    }
}
